package proyecto.dao;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import proyecto.excepcion.DAOExcepcion;
import proyecto.modelo.Sala;

public class SalaDAOImpl extends HibernateDaoSupport implements SalaDAO {
	protected Log log = LogFactory.getLog(getClass());

	private DataSource dataSource;

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@SuppressWarnings("unchecked")
	public List<Sala> listar() throws DAOExcepcion {
		log.info("listar()");
		List<Sala> lista = new ArrayList<Sala>();
		try {
			lista = getHibernateTemplate().find("from Sala");
		} catch (DataAccessException e) {
			log.error(e.toString());
			throw new DAOExcepcion(e.getMessage());
		}
		return lista;
	}

	public Sala obtener(String coSala) throws DAOExcepcion {
		log.info("obtener() : " + coSala);
		Sala modelo = new Sala();
		try {
			modelo = (Sala) getHibernateTemplate().find(
					"from Sala a where trim(a.coSala) = ?",
					coSala).get(0);
		} catch (Exception e) {
			log.error("Error: " + e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
		return modelo;
	}

	public Sala actualizar(Sala modelo) throws DAOExcepcion {
		try {
			getHibernateTemplate().update(modelo);
			getHibernateTemplate().flush();
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
		return modelo;
	}

	public Sala insertar(Sala modelo) throws DAOExcepcion {
		try {
			getHibernateTemplate().save(modelo);
			getHibernateTemplate().flush();
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
		return modelo;
	}

	public void eliminar(String coSala) throws DAOExcepcion {
		Sala modelo = new Sala();
		modelo.setCoSala(coSala);
		try {
			getHibernateTemplate().delete(modelo);
			getHibernateTemplate().flush();
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	public List<Sala> buscar(String cine, String tipo) throws DAOExcepcion {
		log.info("buscar() : " + cine + "," + tipo );
		List<Sala> lista = null;
		try {
			lista = getHibernateTemplate().find(
					"from Sala a where trim(a.cine.coCine) like ? and trim(a.tipo) like ?",
					new Object[]{cine, tipo});
		} catch (Exception e) {
			log.error("Error: " + e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
		return lista;
	}
}
